//
//  XWSegmentedControl.m
//  CELSP
//
//  Created by wzl on 16/6/2.
//  Copyright © 2016年 hq88. All rights reserved.
//

#import "XWSegmentedControl.h"

@interface XWSegmentedControl  ()
/** 选项栏 */
@property (nonatomic,strong) UISegmentedControl *mySegmentCtrl;

@end

@implementation XWSegmentedControl
#pragma mark - 父类方法重写
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self xw_defaultValueInit];
    }
    
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self xw_defaultValueInit];
    }
    
    return self;
}

//绘制底部边线
-(void)drawRect:(CGRect)rect{
    if(_isHasTitleBottomLine){//绘制底部线条
        switch (_lineStyle) {
            case XWSegmentedControlLineStyleEqualWidth:
                [self xw_drawBottomLineWithStyleEqualWidth];
                break;
            case XWSegmentedControlLineStyleEqualTitle:
                [self xw_drawBottomLineWithStyleEqualTitle];
                break;
            case XWSegmentedControlLineStyleDefault:
                [self xw_drawBottomLineWithStyleEqualWidth];
                break;
            default:
                break;
        }
    }
    
    if(_isHasTitleCenterLine){//绘制title之间的线条
        [self xw_drawCenterLine];
    }
}

#pragma mark - 私有方法
- (void)xw_initMySubViews{
    if (_mySegmentCtrl) {
        [_mySegmentCtrl removeFromSuperview];
        _mySegmentCtrl = nil;
    }
    
    _mySegmentCtrl = [[UISegmentedControl alloc] initWithItems:_titles];
    [_mySegmentCtrl addTarget:self action:@selector(xw_mySegmentCtrlValueChanged:) forControlEvents:UIControlEventValueChanged];
    self.selectSegmentIndex = 0;
    
    [self addSubview:_mySegmentCtrl];
    
    //去掉边框 设置文字选中和非选中的颜色
    _mySegmentCtrl.tintColor = [UIColor clearColor];
    NSDictionary *selectedTextAttributes = @{
                                             NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
                                             NSForegroundColorAttributeName : [UIColor colorWithRed:8 / 255.0f
                                                                                              green:169 / 255.0f
                                                                                               blue:204 / 255.0f
                                                                                              alpha:1.0]
                                             };
    NSDictionary *unselectedTextAttributes = @{
                                               NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
                                               NSForegroundColorAttributeName : [UIColor colorWithRed:150 / 255.0f
                                                                                                green:150 / 255.0f
                                                                                                 blue:150 / 255.0f
                                                                                                alpha:1.0]
                                               };
    
    [self setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [self setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
    
    //    添加视图约束
    _mySegmentCtrl.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_mySegmentCtrl]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_mySegmentCtrl)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_mySegmentCtrl]-1-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_mySegmentCtrl)]];
}

//控件默认值初始化
- (void)xw_defaultValueInit{
    self.backgroundColor = [UIColor whiteColor];
    self.selectSegmentIndex = 0;
    self.lineWidth = 2.0f;
    self.isHasTitleBottomLine = YES;
    self.isHasTitleCenterLine= NO;
    self.normalLineColor = [UIColor colorWithRed:235 / 255.0f
                                           green:235 / 255.0f
                                            blue:235 / 255.0f
                                           alpha:1.0];
    self.selectLineColor = [UIColor colorWithRed:8 / 255.0f
                                           green:169 / 255.0f
                                            blue:204 / 255.0f
                                           alpha:1.0];
}

//显示当前选择的页面 隐藏其他页面
- (void)xw_showViewWithSegmentIndex:(NSInteger)segmentIndex{
    NSInteger i = 0;
    for (UIView*view in _views) {
        if (i == segmentIndex) {
            view.hidden = NO;
        }
        else{
            view.hidden = YES;
        }
        
        i++;
    }
}

//选项栏当前选择发生变化时触发
- (void)xw_mySegmentCtrlValueChanged:(id)sender{
    
    _selectSegmentIndex = _mySegmentCtrl.selectedSegmentIndex;
    [self xw_showViewWithSegmentIndex:_selectSegmentIndex];
    [self setNeedsDisplay];
    
    if ([_delegate respondsToSelector:@selector(segmentedControl:didSelectSegmentIndex:)]) {
        [_delegate segmentedControl:self didSelectSegmentIndex:_selectSegmentIndex];
    }
}

- (CGFloat)xw_getSelectTitleWidthWithIndex:(NSUInteger) index{
    NSString*title = _titles[index];
    NSDictionary *selectedTextAttributes = [_mySegmentCtrl titleTextAttributesForState:UIControlStateSelected];
    CGFloat titleWidth = [title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, self.bounds.size.height) options:NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingTruncatesLastVisibleLine attributes:selectedTextAttributes context:nil].size.width;
    
    return titleWidth;
}

#pragma mark 底部线条按样式绘制
//绘制各个线条相等的样式
- (void)xw_drawBottomLineWithStyleEqualWidth{
    //获得处理的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineCap(context, kCGLineCapSquare);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextBeginPath(context);
    
    CGFloat x = 0;
    CGFloat y = self.frame.size.height - self.lineWidth;
    CGFloat width = self.frame.size.width/_titles.count;
    
    for (NSInteger i = 0; i < _titles.count; i++) {
        //设置选中和未选中的颜色
        if (i== _selectSegmentIndex) {
            CGContextSetStrokeColorWithColor(context, self.selectLineColor.CGColor);
        }
        else{
            CGContextSetStrokeColorWithColor(context, self.normalLineColor.CGColor);
        }
        
        CGContextMoveToPoint(context, x, y);
        x +=width;//绘制终点的x坐标
        CGContextAddLineToPoint(context, x, y);
        CGContextStrokePath(context);
    }
}

//与标题文字所占的宽度相等
- (void)xw_drawBottomLineWithStyleEqualTitle{
    //获得处理的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineCap(context, kCGLineCapSquare);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextBeginPath(context);
    
    CGFloat x = 0;
    CGFloat y = self.frame.size.height - self.lineWidth;
    CGFloat width = self.frame.size.width/_titles.count;
    
    for (NSInteger i = 0; i < _titles.count; i++) {
        //设置选中和未选中的颜色
        if (i== _selectSegmentIndex) {
            CGFloat titleWidth = [self xw_getSelectTitleWidthWithIndex:i];
            //第一段绘制
            CGContextMoveToPoint(context, x, y);
            CGContextSetStrokeColorWithColor(context, self.normalLineColor.CGColor);
            x += floor((width-titleWidth)/2);
            CGContextAddLineToPoint(context, x, y);
            CGContextStrokePath(context);
            //第二段绘制
            CGContextMoveToPoint(context, x, y);
            CGContextSetStrokeColorWithColor(context, self.selectLineColor.CGColor);
            x += titleWidth;
            CGContextAddLineToPoint(context, x, y);
            CGContextStrokePath(context);
            //第三段绘制
            CGContextMoveToPoint(context, x, y);
            CGContextSetStrokeColorWithColor(context, self.normalLineColor.CGColor);
            x = width*(i+1);
            CGContextAddLineToPoint(context, x, y);
            CGContextStrokePath(context);
            
        }
        else{
            CGContextSetStrokeColorWithColor(context, self.normalLineColor.CGColor);
        }
        
        CGContextMoveToPoint(context, x, y);
        x +=width;//绘制终点的x坐标
        CGContextAddLineToPoint(context, x, y);
        CGContextStrokePath(context);
    }
}

//绘制标题之间的分隔线
- (void)xw_drawCenterLine{
    //获得处理的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineCap(context, kCGLineCapSquare);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, self.normalLineColor.CGColor);
    
    CGFloat width  = self.frame.size.width/_titles.count;
    CGFloat height = self.frame.size.height*0.7f;
    CGFloat x = 0;
    CGFloat y = (self.frame.size.height - height)/2.0f;
    
    for (NSInteger i = 0; i < _titles.count-1; i++) {
        x += width;
        CGContextMoveToPoint(context, x, y);
        CGContextAddLineToPoint(context, x, y+height);
        CGContextStrokePath(context);
    }
}

#pragma mark - 公开方法
- (void)setSegmentedControlTitles:(NSArray *)titles andViews:(NSArray *)views{
    self.titles = titles;
    self.views = views;
    [self xw_initMySubViews];
    [self xw_showViewWithSegmentIndex:_selectSegmentIndex];
    
}

- (void)setSelectSegmentIndex:(NSInteger)selectSegmentIndex{
    _selectSegmentIndex = selectSegmentIndex;
    self.mySegmentCtrl.selectedSegmentIndex = selectSegmentIndex;
}

- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment{
    [self.mySegmentCtrl setTitle:title forSegmentAtIndex:segment];
}

-(void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state{
    [_mySegmentCtrl setTitleTextAttributes:attributes forState:state];
}
@end
